# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymongo

from slave_requests.settings import mongoDB_db, mongoDB_host, mongoDB_port, mongoDB_username, mongoDB_password


class SlaveRequestsPipeline(object):
    def process_item(self, item, spider):
        return item


class MongoDBPipeline(object):

    def __init__(self, mongo_host, mongo_port, username, password):
        self.mongo_host = mongo_host
        self.mongo_port = mongo_port
        self.username = username
        self.password = password
        self.mongo_db = mongoDB_db
        self.client = None
        self.db = None
        
    @classmethod
    def from_crawler(cls, crawler):
        
        return cls(
            mongo_host=mongoDB_host,
            mongo_port=mongoDB_port,
            username=mongoDB_username,
            password=mongoDB_password
        )
    
    def open_spider(self, spider):

        self.client = pymongo.MongoClient(
            f'mongodb://{self.username}:{self.password}@{self.mongo_host}:{self.mongo_port}'
        )
        self.db = self.client[self.mongo_db]
        
    def close_spider(self, spider):
        # 爬虫关闭,数据库跟着关闭
        self.client.close()

    def process_item(self, item, spider):
        # 将item数据保存在mongo中
        self.db[f'{item["subject"]}_{item["city"]}'].insert_one(dict(item))

        return item
